package com.example.excelreader

import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.dom4j.DocumentHelper
import org.dom4j.io.OutputFormat
import org.dom4j.io.SAXReader
import org.dom4j.io.XMLWriter
import java.io.File
import java.io.FileOutputStream

fun main(args: Array<String>) {
    val filePath = "F:\\短信验证v1.XLSX"
    val dir = "F:\\strings"
    MyClass().run(filePath, dir/*args[0], args[1]*/)
}

class MyClass {
    private val dirMap = mapOf("English" to "values", "Cs" to "values-zh-rCN", "Ct" to "values-zh-rTW", "German" to "values-de"
            , "French" to "values-fr", "Indonesian" to "values-in", "Italian" to "values-it", "Japanese" to "values-ja",
            "Korean" to "values-ko", "Portuguese" to "values-pt", "Russian" to "values-ru", "Spanish" to "values-es"
    )

    fun run(filePath: String, dir: String) {
//
        val excelData = readFromExcel(filePath)

        appendXml(excelData, dirMap, dir)

    }


    private fun appendXml(data: ArrayList<Array<String?>>?, map: Map<String, String>, libDir: String) {
        if (data == null) return

        var languageArray: Array<String?> = data[0]
        languageArray.forEach {
            if (!it.isNullOrEmpty()) {
                val xmlFile = "$libDir\\${map[it]}_strings.xml"// "$libDir\\src\\main\\res\\${map[it]}\\strings.xml"
                var valueIndex: Int = 0
                languageArray.forEachIndexed { index, s ->
                    if (s.equals(it)) {
                        valueIndex = index
                        return@forEachIndexed
                    }
                }
                writeToXml(data, valueIndex, xmlFile)
            }
        }


    }

    private fun appendXml(data: ArrayList<Array<String?>>, index: Int, xmlFile: String) {
        val saxReader = SAXReader()
        val rootElement = saxReader.read(File(xmlFile)).rootElement

        data.forEach {
            val key = it[0]
            val value = it[index]
            if (!key.isNullOrEmpty())
                rootElement.addElement("string").addAttribute("name", key).addText(value)
            println("apped:$key, $value")
        }

        val format = OutputFormat()
        format.setIndentSize(2)
        format.isTrimText = false
        format.isPadText = false
        format.isNewlines = true
        format.lineSeparator = "\r"
        val xmlWriter = XMLWriter(FileOutputStream(File(xmlFile)), format)
        xmlWriter.write(rootElement)
    }

    private fun writeToXml(data: ArrayList<Array<String?>>, index: Int, xmlFile: String) {

        val document = DocumentHelper.createDocument()
        val rootElement = document.addElement("resources")

        data.forEach {
            val key = it[0]
            val value = it[index]
            if (!key.isNullOrEmpty())
                rootElement.addElement("string").addAttribute("name", key).addText(value)
        }
        val xmlWriter = XMLWriter(FileOutputStream(File(xmlFile)), OutputFormat.createPrettyPrint())
        xmlWriter.write(document)
    }

    private fun readFromExcel(filePath: String): ArrayList<Array<String?>>? {
        val workBook = File(filePath).inputStream().use {
            when (filePath.substring(filePath.lastIndexOf("."))) {
                ".xls" -> {
                    HSSFWorkbook(it)
                }
                ".xlsx", ".XLSX" -> {
                    XSSFWorkbook(it)
                }
                else -> {
                    null
                }
            }
        } ?: return null

        val sheet = workBook.getSheetAt(0)
        val rowNum = sheet.physicalNumberOfRows - 1
        val excelData = ArrayList<Array<String?>>(rowNum + 1)
        for (i in 0..rowNum) {
            val row = sheet.getRow(i)
            val columns = row.physicalNumberOfCells - 1
            val rowData = arrayOfNulls<String>(columns + 1)
            for (j in 0..columns) {
                val cell = row.getCell(j)
                val value = when (cell?.cellType) {
                    Cell.CELL_TYPE_STRING -> cell.richStringCellValue.toString()
                    else -> ""
                }
                rowData[j] = value
            }
            excelData.add(rowData)
        }
        return excelData
    }


}